﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tippelde.Services.Dtos;
using Tippelde.Services.Teams;

namespace Tippelde.Web.Controllers
{
    [Authorize]
    public class TeamController : Controller
    {
        [Dependency]
        public ITeamManager TeamManager { get; set; }

        [Authorize(Roles = "teammanager,admin")]
        public ActionResult Index(int? page)
        {
            var model = TeamManager.GetAllTeamHeaders(page);
            return View(model);
        }

        [Authorize(Roles = "teammanager,admin")]
        public ActionResult Create(bool? partial)
        {
            ViewBag.ActionName = "Create";
            if (partial ?? false)
                return PartialView("_EditorPartial");
            return View("Editor");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "teammanager,admin")]
        public ActionResult Create(TeamHeaderData model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    TeamManager.CreateTeam(model);
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex);
                }
            }
            return View("Editor", model);
        }

        public JsonResult Search(string q)
        {
            var model = TeamManager.GetAllTeamHeadersStartsWith(q);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "teammanager,admin")]
        public ActionResult Edit(int Id, bool? partial)
        {
            ViewBag.ActionName = "Edit";
            var model = TeamManager.GetTeamHeader(Id);
            if (partial ?? false)
                return PartialView("_EditorPartial", model);
            return View("Editor", model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "teammanager,admin")]
        public ActionResult Edit(int Id, TeamHeaderData model)
        {
            model.Id = Id;
            if (ModelState.IsValid)
            {
                try
                {
                    TeamManager.EditTeam(model);
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex);
                }
            }
            return View("Editor", model);
        }

    }
}